package com.probiz.estore.webapp.action;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.acegisecurity.ui.AbstractProcessingFilter;
import org.acegisecurity.ui.savedrequest.SavedRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.Constants;
import com.probiz.estore.cart.CheckoutConstants;
import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.system.AppUser;
import com.probiz.estore.common.service.LoginNtService;
import com.probiz.estore.core.controller.BaseController;
import com.probiz.estore.webapp.util.RequestContext;

/**
 */
public class PostLoginController extends BaseController {

	private LoginNtService loginNtService;
	
	public void setLoginNtService(LoginNtService loginNtService) {
		this.loginNtService = loginNtService;
	}

	public ModelAndView defaultAction(HttpServletRequest request, HttpServletResponse response) throws ServletException {
		AppUser appUser = (AppUser) RequestContext.getCurrentUser();
		String targetUrl = getTargetUrl(request, request.getSession(true), appUser);
		loginNtService.afterLogin(request, response, appUser);
		try {
			response.sendRedirect(response.encodeRedirectURL(targetUrl));
			return null;
		} catch (Throwable e) {
			logger.error("Cannot sendRedirect to target page after logined: " + targetUrl, e);
		}
		return null;
	}

	private String getTargetUrl(HttpServletRequest req, HttpSession session, AppUser appUser) {
		// retrieve saved requested url (saved by Acegi)
		String targetUrl = null;
		// retrieve saved requested url (saved by Acegi)
		if (session != null) {
			SavedRequest sq = (SavedRequest) session.getAttribute(AbstractProcessingFilter.ACEGI_SAVED_REQUEST_KEY);
			if (sq != null) {
				targetUrl = sq.getFullRequestUrl();
				session.removeAttribute(AbstractProcessingFilter.ACEGI_SAVED_REQUEST_KEY);
			}
		}

		if (targetUrl == null || "".equals(targetUrl)) {
			String continueUrl = (String) session.getAttribute(Constants.SAVED_REQUEST_KEY);
			if (StringUtils.isNotBlank(continueUrl)) {
				if (continueUrl.contains("register.html")) {
					// 解决注册完后点最顶链接登录出错的BUG
					targetUrl = req.getContextPath() + "/customer/index.html";
				} else if (continueUrl.contains("resetPassword")) {
					// 解决取回密码后点最顶链接登录出错的BUG
					targetUrl = req.getContextPath() + "/customer/index.html";
				} else {
					targetUrl = continueUrl;
				}
			} else {
				// if no requested url, set to use default url
				targetUrl = req.getContextPath() + "/index.html";
			}
		}

		if (StringUtils.isNotBlank(targetUrl) && targetUrl.contains("blank")) {
			// 解决ajax获取内容的时候要重新登录的问题
			if (RequestContext.isFront()) {
				targetUrl = req.getContextPath() + "/customer/index.html";
			} else {
				targetUrl = req.getContextPath() + "/index.html";
			}
		}
		
		
		if (RequestContext.isFront()) {
			// make sure that the amdin use cant login front page here.
			if (appUser.isContainAdminRole()) {
				targetUrl = req.getContextPath() + "/admin/index.html";
			}
			Object toCe = session.getAttribute(CheckoutConstants.TOCHECKOUT);
			if (toCe != null) {
				boolean toCheckout = Boolean.valueOf(toCe.toString());
				if (toCheckout) {
					session.removeAttribute(CheckoutConstants.TOCHECKOUT);
					targetUrl = req.getContextPath() + "/checkout.html";
				}
			}
			
		} else {
			// checking the system parameter cofiguration when the login user
			// hold the admin role
			if (appUser.isContainAdminRole() && ConfigUtil.getInstance().checkInvalidSystemConfigs()) {
				logger.info("There are invalid system configs, forwarding to system config page...");
				targetUrl = "system/systemConfig.html";
			} else if (targetUrl.indexOf("siteMessage") >= 0) {
				// 如果是系统提醒信息，则不需要返回此页面，因是json返回
				targetUrl = req.getContextPath() + "/";
			}

		}
		return targetUrl;
	}

}